package com.edu.servlet;

import com.edu.bean.User;
import com.edu.service.AdminUserService;
import com.edu.util.MD5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/admin/login")
public class AdminLoginServlet extends HttpServlet {
    private AdminUserService adminUserService = new AdminUserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取session，如果已登录则直接跳转到首页
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute("adminUser") != null) {
            response.sendRedirect(request.getContextPath() + "/admin/index.jsp");
            return;
        }
        // 未登录则转发到登录页
        request.getRequestDispatcher("/admin/login.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String roleIdStr = request.getParameter("roleId");

        // 参数校验
        if (username == null || password == null || roleIdStr == null ||
                username.trim().isEmpty() || password.trim().isEmpty() || roleIdStr.trim().isEmpty()) {
            request.setAttribute("error", "请填写完整的登录信息");
            request.getRequestDispatcher("/admin/login.jsp").forward(request, response);
            return;
        }

        try {
            int roleId = Integer.parseInt(roleIdStr);
            // 密码MD5加密
            String md5Password = MD5Util.md5(password);

            // 验证用户身份
            User user = adminUserService.adminLogin(username, md5Password, roleId);

            if (user != null) {
                // 登录成功，将用户信息存入session
                HttpSession session = request.getSession();
                session.setAttribute("adminUser", user);
                response.sendRedirect(request.getContextPath() + "/admin/index.jsp");
            } else {
                // 登录失败
                request.setAttribute("error", "用户名、密码或角色错误");
                request.getRequestDispatcher("/admin/login.jsp").forward(request, response);
            }
        } catch (NumberFormatException e) {
            request.setAttribute("error", "角色信息错误");
            request.getRequestDispatcher("/admin/login.jsp").forward(request, response);
        }
    }
}